const { pool } = require('../config/db');

/**
 * 1. 获取分类列表（树形结构，支持多级分类）
 * 用途：前端下拉选择分类、分类导航栏
 */
exports.getCategoryTree = async (req, res, next) => {
  try {
    // 1. 查询所有分类
    const [categories] = await pool.query(
      'SELECT id, questionname AS name, pid FROM questioncata ORDER BY pid, id'
    );

    // 2. 构建树形结构（递归处理多级分类）
    const buildTree = (pid = null) => {
      return categories
        .filter(cat => cat.pid === pid)
        .map(cat => ({
          id: cat.id,
          name: cat.name,
          // 递归获取子分类
          children: buildTree(cat.id)
        }));
    };

    // 3. 根分类的子分类就是顶级分类（pid=0）
    const categoryTree = buildTree(0);

    res.status(200).json({
      code:200,
      msg:'分类树获取失败',
      data: { categoryTree }
    });

  } catch (err) {
    console.error('获取分类树错误:', err);
    next(err);
  }
};

/**
 * 2. 按分类筛选问题（支持分页）
 * 用途：前端点击分类，查看该分类下的所有问题
 */
exports.getQuestionsByCategory = async (req, res, next) => {
  try {
    // 1. 获取请求参数：分类ID、页码、每页数量
    const { categoryId } = req.params; // 路径参数：/categories/:categoryId/questions
    const page = parseInt(req.query.page) || 1; // 默认第1页
    const pageSize = parseInt(req.query.pageSize) || 10; // 默认每页10条
    const offset = (page - 1) * pageSize; // 计算偏移量

    // 2. 查询该分类下的问题总数（用于分页）
    const [countResult] = await pool.query(
      'SELECT COUNT(*) AS total FROM questions WHERE category_id = ?',
      [categoryId]
    );
    const total = countResult[0].total;
    const totalPages = Math.ceil(total / pageSize);

    // 3. 查询该分类下的问题列表（关联用户表，显示提问者信息）
    const [questions] = await pool.query(
      `SELECT q.id, q.title, q.content, q.view_count, q.answer_count, 
              q.is_solved, q.created, u.username AS question_user,
              c.questionname AS category_name
       FROM questions q
       LEFT JOIN users u ON q.user_id = u.id
       LEFT JOIN questioncata c ON q.category_id = c.id
       WHERE q.category_id = ?
       ORDER BY q.created DESC
       LIMIT ? OFFSET ?`,
      [categoryId, pageSize, offset]
    );

    res.status(200).json({
      code:200,
      success: true,
      data: {
        questions,
        pagination: {
          page,
          pageSize,
          total,
          totalPages
        }
      }
    });

  } catch (err) {
    console.error('按分类筛选问题错误:', err);
    next(err);
  }
};

/**
 * 3. 获取单个分类的详情（含子分类）
 * 用途：前端查看分类详情、统计该分类下的问题数
 */
exports.getCategoryDetail = async (req, res, next) => {
  try {
    const { id } = req.params; // 分类ID

    // 1. 查询分类基本信息
    const [category] = await pool.query(
      'SELECT id, questionname AS name, pid FROM questioncata WHERE id = ?',
      [id]
    );
    if (category.length === 0) {
      const error = new Error('分类不存在');
      error.statusCode = 404;
      throw error;
    }

    // 2. 查询该分类下的问题总数
    const [questionCount] = await pool.query(
      'SELECT COUNT(*) AS total_questions FROM questions WHERE category_id = ?',
      [id]
    );

    // 3. 查询该分类的子分类
    const [children] = await pool.query(
      'SELECT id, questionname AS name FROM questioncata WHERE pid = ?',
      [id]
    );

    res.status(200).json({
      success: true,
      data: {
        category: {
          id: category[0].id,
          name: category[0].name,
          pid: category[0].pid,
          total_questions: questionCount[0].total_questions,
          children
        }
      }
    });

  } catch (err) {
    console.error('获取分类详情错误:', err);
    next(err);
  }
};